home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-13 / me_cd22.zip / DOC.ZIP / UNDO.ART < prev   
Text File  |  1992-04-27  |  28KB  |  672 lines

  1. -*-text-*-
  2.  
  3.  
  4.           Implementing Undo for Text Editors
  5.           ------------ ---- ---    ---- -------
  6.  
  7.                 Craig Durland
  8.                craig@cv.hp.com
  9.                 Copyright 1991
  10.  
  11.  
  12.                 February 1991
  13.                    Revised
  14.                September 1991   
  15.                 February 1992
  16.  
  17.  
  18. Probably anyone who has used a text editor has at one time or another
  19. made a boo boo and immediately wished they could to go back in time and
  20. not do it all over again.  The Undo command gives that ability by moving
  21. backwards in time, reversing the effects of the most recent changes to
  22. the text.  Some undo commands can go back to the begining of time,
  23. undoing all changes that have occured to the text.
  24.  
  25. The undo described in this article is a subset of the idealized undo -
  26. it only reverses changes to text.  It doesn't keep track of cursor
  27. movements, buffer changes or the zillions of other things we do while
  28. editing text.  While this can make undoing changes disconcerting because
  29. it can jump from change to change differently from what you remember, it
  30. also reduces the amount of stuff that the editor needs to remember
  31. (saving memory) and helps keep the editor from bogging down trying to
  32. keep track of whats been going on.  Finally, the material presented is
  33. for text editors.  Editors of other types may find some of the
  34. discussion relevant but that will be a happy accident.
  35.  
  36. Jonathan Payne (author of JOVE) has stated that "Undo/redo is trivial to
  37. implement" (comp.editors, Tue, 2 Jan 1990).  Having just implemented
  38. undo for the editor I am working on, I think that straight forward is a
  39. better term than trival.  Since it took me a long time to figure out a
  40. workable undo scheme, I thought others might be interested in what I
  41. did.
  42.  
  43.  
  44.  
  45. Caveats:  The algorithms, code and data structures used in this article
  46. are based on working and tested code that has been "sanitized" to remove
  47. obscuring details (like what stack data structures I used).  If you use
  48. the code, make sure you understand it so that you can properly fill in
  49. the missing details.
  50.  
  51. Conditions:  You are free to use the algorithms, code and data
  52. structures contained in this article in anyway you please.  If you use
  53. large chunks, I would appreciate an acknowledgment.  If you distribute
  54. this article, in whole or part, please retain the authorship notice.
  55.  
  56.  
  57.  
  58.             What is Not Discussed
  59.             ---- --    --- ---------
  60.  
  61. Redo is a undo for undo.  Very handy if you undo one time to many and
  62. need to undo that last undo.  I haven't implemented it yet but I think
  63. that it will be easy to modify the algorithms to support it.  I also
  64. think some dragons are there but they are hiding from me.  We'll see
  65. when I actually get around to doing it.
  66.  
  67.  
  68.  
  69.        Editor Implementations and How They Affect Undo
  70.        ------ --------------- --- --- ---- ------ ----
  71.  
  72. Two popular ways text editors store text are "buffer gap" and "linked
  73. list of lines" (described in detail else where - see comp.editors).  As
  74. you might imagine, different implementations for storing text can affect
  75. undo implementations.  Fortunately for this article, the affects are
  76. relatively minor.  As I discuss data structures and algorithms, I will
  77. point out the differences.
  78.  
  79. Note:  I will refer to buffer gap editors as BGE and linked list editors
  80. as LLE.
  81.  
  82.  
  83.            What You Need to Save to Implement Undo
  84.            ---- ---    ---- --    ---- --    --------- ----
  85.  
  86. I use Undo Events to represent text changes.  These events are kept in a
  87. undo stack, most recent event at the top of the stack.  There is one
  88. stack per text object (buffer in Emacs) so undo can only track changes
  89. on a per buffer basis.  This simplifies things quite a bit over tracking
  90. all changes globally in a multibuffer editor.
  91.  
  92. I found that four event types seem to be enough describe all text
  93. changes.  They are:
  94. - BU_INSERT:  This event is used when text is inserted.  The most common
  95.   case is when you type.  When text is inserted, we need to remember how
  96.   much was inserted and where it was inserted.  We don't need to
  97.   remember the what the text was because to undo this type of event, all
  98.   we have to do is delete the inserted text.  Note that in order to
  99.   reduce the number of events saved (and memory used), you need to be
  100.   able to detect text that is inserted sequentially (like when you type
  101.   "123") so that all these events can packed into one event.  This can
  102.   affect more than you would think at first glance and will be descussed
  103.   more fully else where.
  104.  
  105. - BU_DELETE:  This event is used when text is deleted, for example when
  106.   you use the delete (or backspace) key.  Here we need to remember the
  107.   place where the deletion took place and the text to be deleted.  Note
  108.   that we have to save the text before (or while) it is deleted.  This
  109.   is can cause trouble for some editor implementations.  Again, event
  110.   packing can save much of space if users like to lean on the delete
  111.   key.  To undo a delete, we have to insert the deleted text at the
  112.   place where it was deleted.
  113.  
  114. - BU_SP:  A sequence point is a stopping point in the undo stack.  It
  115.   tells the undo routine that this is the last event to undo so the user
  116.   will think that one of his actions has been undone.  Note that this
  117.   implies that one user action may cause one or (many) more undo events
  118.   to be saved.  This is especially true when the editor supports macros
  119.   or an extension language.  I think that it is important that one press
  120.   of the undo key undoes one user action (there are a few exceptions
  121.   (like query replace)).  Probably one of the hardest things to "get
  122.   right" (from the users point of view) is where to place sequence
  123.   points.  Here is my list of rules for sequence points (take these with
  124.   a grain of salt - these are my opinions with nothing to back them up.
  125.   They may change.):
  126.   - Need sequence points so undoing stops at "natural, expected" places.
  127.   - Undo should stop where user explicitly marked the buffer as
  128.     unchanged (like save buffer to disk).  These are usually UNCHANGED
  129.     events.
  130.   - A string of self insert keys should undo as one.  Its pretty
  131.     annoying to have to hit undo 14 times to undo "this is a test".
  132.   - A word wrap or Return should break a character stream.  Thus undo
  133.     only backs up a line at at time, probably better than undoing an
  134.     entire paragraph when only one line needed undoing.
  135.   - Commands, macros, programs written in the extension language, etc
  136.     should undo as a unit.  ie if pressing a key caused a bunch of stuff
  137.     to happen, pressing undo should undo all the stuff the key caused.
  138.   - Since rules can't cover all cases (like query replace), programs
  139.     need to be able to add sequence points.
  140.  
  141.   I also store the buffer modifed state here so I know to mark the
  142.   buffer as unchanged if it was before this change happened.
  143.  
  144. - BU_UNCHANGED:  This event marks a time when the text was marked as
  145.   unchanged or saved.  Examples include saving the text to the disk.
  146.   When undoing, this event marks a stopping point:  The user has undoed
  147.   back to a time when the buffer was "safe".  When you make an
  148.   inadvertent change to text that you only wanted to look at, it is
  149.   psychologically reasuring to know the text is back to its original
  150.   state.
  151.  
  152.   Only the most recent unchanged event actually indicates that the
  153.   buffer contents match those out on the disk (and every buffer change
  154.   before and after that event means the buffer is out of sync with the
  155.   disk).  For undo, this means that only the most recent unchanged event
  156.   is valid - when that event is undone, the buffer matches the disk.
  157.   After that one, other unchanged events need to be ignored because the
  158.   buffer at that point can't match the disk.
  159.  
  160.   Note that BU_UNCHANGED events are really just special cases of
  161.   sequence points.  You could easily just combine them into one event.
  162.  
  163. It should be obvious by now that much editing would generate a LOT of
  164. undo events.  Unless your computer has an infinite amount of memory, you
  165. need some rules about when to start throwing away events.  Since
  166. different people will have different ideas about this and the amount of
  167. memory can greatly affect this, you need to let the user control it.
  168. There are three parameters that need to be specified:
  169. - Save or don't save undos.  For Emacs-like editors, there are probably
  170.   many buffers that don't need (or want) undo.  For example, I don't
  171.   care if help buffers have undo.  Not turning on undo for all buffers
  172.   can really save memory and help performance (undo can really slow down
  173.   extension programs).
  174. - The maximum amount of text saved.  When text is deleted, it has to be
  175.   saved somewhere.  The more deleted, the more that needs to saved.  It
  176.   adds up.  We need a point where we discard some of the old saved text
  177.   in order to save some.  Note that a big delete can clean out all the
  178.   existing undos and worst case, the delete is bigger than the max so we
  179.   have to throw away the undos and ignore the delete (because there is
  180.   not enough room to save it).
  181. - The maximum number of events saved.  Each event takes up a bit of
  182.   memory.  Events pile up amazingly fast during editing.  At some point
  183.   we have to start throwing away the old to make room for the new (kinda
  184.   like my garage).  When dumping events, you have to also clean up any
  185.   text the deleted event might have saved.
  186.  
  187. It can be a real guessing game to figure out how to balance the number
  188. of events saved against text saved.  Different editing operations use up
  189. one or the other at different rates.  I'm currently using 600 events and
  190. a 5K save buffer.
  191.  
  192.  
  193.  
  194.  
  195.  
  196.                When an Editor Does Undo
  197.                ---- -- ------ ---- ----
  198.  
  199. Given the undo event types and rules, the editor just has to save undo
  200. events when needed and add sequence points at the "proper" times.  Now
  201. is the time you will be glad you funneled all you buffer changes through
  202. just a couple of insert/delete routines.  Here is where I save events
  203. for my Emacs-like editor:
  204. - Insert a block of text.        save_for_undo(BU_INSERT,n);
  205.   This routine is used when doing things like a kill buffer yank.  It is
  206.   also used to undo a delete so care has to be taken not to get into a
  207.   do/undo tug of war.
  208. - Read a file.                save_for_undo(BU_UNCHANGED,0);
  209.   We mark the buffer as unchanged because it has been cleared and filled
  210.   with new text.  Note that it is up the buffer clear routine to save
  211.   the delete text.  Also note that to do a "real" undo, we should also
  212.   save_for_undo(BU_INSERT,<characters in file>).  I don't because I
  213.   don't think it makes sense and because of the clear buffer problem
  214.   mentioned below.
  215. - Insert n characters.            save_for_undo(BU_INSERT,n);
  216.   This is used for the self inserting characters.
  217. - Delete n characters.            save_for_undo(BU_DELETE,n);
  218.   Have to be careful here because this routine is also used to undo
  219.   character inserts.  Actually, the undo routine is the one who cares
  220.   and protects against this.
  221. - After a key has been processed.    save_for_undo(BU_SP,0);
  222. - Mark a buffer as unchanged.        save_for_undo(BU_UNCHANGED,0);
  223. - Save a file.  This routine doesn't need to do anything because it
  224.   calls the buffer_is_unchanged() routine.  That routine saves the event.
  225.  
  226. Where I should (but don't) save undo events:
  227. - Clear buffer.  Because its hard to do with my type of editor.  See
  228.   below for more on this.  Other editors would not have this routine and
  229.   would just use delete.  Instead, I clear all undos.
  230.  
  231. To do undo, the editor just calls the undo routine.
  232.  
  233.  
  234.  
  235.                Data Structures
  236.                ----    ----------
  237.  
  238. Each text object (buffer) has a pointer to a undo header.  This header
  239. contains a undo event stack, number of events in the stack (so I can
  240. easily check to see if the stack has grown too big), a flag that
  241. indicates whether or not the BU_UNCHANGED events are valid and an area
  242. in which to save deleted text.
  243.  
  244. In C, this looks like:
  245.      typedef struct
  246.      {
  247.        Undo *undo_stack;    /* where the undo events are */
  248.        int undo_count;        /* number of undos in the stack */
  249.        int there_is_a_valid_unchanged_event;
  250.        Bag *bag;        /* deleted text saved here */
  251.      } UndoHeader;
  252.  
  253. An undo stack is a linked list of undo events.  I used a linked list
  254. because it was easy and worked well but there are many other ways to
  255. store the data that would probably work as well.  An event contains a
  256. pointer to the next (older) event, the event type (BU_INSERT, etc), a
  257. marker to where the event took place, the number of characters involved
  258. and a pointer to the saved text (if any).  Note that some events may not
  259. use some of these fields.  The clever programmer could probably save
  260. quite a bit of space by having different (sized) structures for each
  261. event type.
  262.  
  263. LLEs (Linked List Editors) can run into problems when asked to save
  264. delete events.  Its quite possible that the we could be asked to save
  265. more text than buffer contains.  For example, in Emacs, the user could
  266. hit control-U a bunch of times and hit the delete key - delete 16384
  267. characters when the buffer only contains 53.  With a BGE (Buffer Gap
  268. Editor), this is very easy to check but is very time consuming with a
  269. LLE.  What I do with LLE is "trust but verify".  I make enough room to
  270. hold that much deleted text, then go ahead and try and save it.  I then
  271. figure out how much I really saved (a side affect of copying the text)
  272. and save that number.  The big drawback with this is that its easy to
  273. clear out most of the undo stack when you didn't need to and looks very
  274. fishy when you can't undo very much.  The other way around this is to
  275. put the "save-deleted-text" stuff in the routine that actually deletes
  276. the text but this would add a lot of noise to a already hard to
  277. understand routine.
  278.  
  279. A problem related to the I-don't-know-how-much-is-going-to-be-deleted
  280. problem is the clear-buffer problem.  With BGE, you know how much you
  281. are going to remove, with LLE, you don't.  So, I just clear the undo
  282. stack when the buffer is cleared because 1) most buffers will probably
  283. be bigger than the undo buffer anyway and cause it to be cleared and 2)
  284. buffer clears don't happen very often - usually for buffer deletes and
  285. file reads.
  286.  
  287. C code:
  288.      typedef struct Undo
  289.      {
  290.        struct Undo *next;    /* pointer to next older event */
  291.        int type;
  292.        UnMark mark;        /* where the event took place */
  293.        int n;            /* number of characters involved */
  294.        char *text;        /* where deleted text is saved */
  295.      } Undo;
  296.  
  297. In my editor, I have the concept of bags.  Bags hold various types of
  298. text objects and I have a lot of builtin support for them.  It was 
  299. natural and very easy to use these to hold deleted text.  Your editor is
  300. probably different so you'll have to use something else (like
  301. malloc()ing some space).  I use one per buffer and holds it all the
  302. deleted text.  The undo delete events point into the bag (actually, I
  303. use offsets but the concept is the same).
  304.  
  305. The undo markers are where in the buffer the event took place.  These
  306. only matter for insert and delete events.  This is one of the areas
  307. where editor implementation really matters.  A BGE (buffer gap editor)
  308. is a real win here.  Since undo events are effectively snapshots of
  309. buffer history, as you undo, the buffer returns to its exact state back
  310. in time.  A BGE mark is just an offset into the buffer.  We can just
  311. store this offset in the event and never mess with it because we know
  312. that it will be correct when we undo to the point where we want to use
  313. it.  We can't do this with a LLE (linked list editor).  A LLE mark is a
  314. pair:  (line pointer, offset in line).  Both editor types have to adjust
  315. marks as text is inserted and deleted but unlike the BGE, LLE marks can
  316. become invalid as time goes on (and lines unlinked).  One example of
  317. this is if you insert text into the middle of a block and then delete
  318. that block.  The delete has unlinked the lines that were inserted so the
  319. marks with insert are invalid.  When you undo the delete, you can't undo
  320. the insert because you no longer know where it took place.  This is not
  321. a problem with BGE because even though the delete made the insert mark
  322. point to the wrong place, when the delete was undoed, the mark became
  323. valid again.
  324.  
  325. To get around this problem a LLE has to either 1) track all cursor
  326. movement or 2) calculate the pair (line number, offset in line).
  327.   1) Pros:  Can undo cursor movements.
  328.      Cons:
  329.        - This would generate bazillions of cursor move events.
  330.        - This could really be a pain in the butt and slow down the
  331.        cursor movement routines.  One of the main reasons for writing a
  332.        LLE is not having to worry about stuff like this.
  333.   2) Pros:
  334.        - Some LLEs might already keep marks like this.
  335.        - You can (sometimes) keep track of this position so that you
  336.        don't have recalculate it all the time.  You would track it when
  337.        you could and mark it as invalid when you couldn't.
  338.        - Its easy to calculate.
  339.        - These marks work just like BGE marks.
  340.        - There are some optimizations that can be made if many events
  341.        are generated (sequentially) for the same line.  Basically, if
  342.        the dot line remains the same, you calculated the line number
  343.        earlier.  Caution - this can be trickier than you think.
  344.      Cons:
  345.        - It takes time to calculate the mark.
  346.        - You have to calculate it a lot.
  347.        - It adds a bunch of piddlie details to try and track the dot
  348.        and greatly increases the chances of screwing up.
  349.  
  350. I chose to do 2) (since my editor is a LLE).  Here is the C code:
  351.      typedef struct
  352.      {
  353.        int line;
  354.        int offset;
  355.      } UnMark;
  356.  
  357. For a BGE, just use the mark type you already have.
  358.  
  359. Some combinations of events occur together frequently and it might be a
  360. win to create an event to take advantage of them.  For example, replace
  361. operations involve a delete and insert at the same place.  If you packed
  362. these two events into one, you could potentially save lots of space in a
  363. big query replace.
  364.  
  365.  
  366.              Alternative Data Structures
  367.              ----------- ---- ----------
  368.  
  369. I've glossed over how I actually store the undo stack.  This is because
  370. there many (good) ways to do it.  I use linked lists because they are
  371. simple.  A more clever and compact method would be to pack the deleted
  372. text into the event structure (using the "clever" technique mentioned
  373. above) and store the event plus text in a fixed size data area.  This
  374. has serveral advantages:  You don't have to worry the number of events -
  375. when you run out space to store them, start removing the old events.  It
  376. is much easier to garbage collect the undo stack during undo.  Its
  377. also easier to make room for a new event.  The disadvantages are that
  378. you have to worry about structure alignment (and machine architecture)
  379. and the some of the code will get messy (in my opinion).  The old trade
  380. off of fast and small versus big and simple (or, as Julie Brown would
  381. say, "I like 'em big and stupid").
  382.  
  383.  
  384.  
  385.  
  386.                Global Variables
  387.                ------ ---------
  388.  
  389. I use a few global variables to make controling undo a little easier.
  390.  
  391. Bool do_undo;
  392.   This variable is TRUE if undo is turned on for the current buffer.
  393.   The switch buffer code sets this so people who need to know can do so
  394.   quickly.  The user can change it by toggling a buffer flag.
  395.  
  396. Buffer *current_buffer;
  397.   Pointer to the buffer where changes are taking place.  The current
  398.   undo header hangs off this buffer.
  399.  
  400. int max_undos = 600;
  401.   The maximum number of undo events.
  402.  
  403. int max_undo_saved = 5000;
  404.   The maximum amount of deleted characters that can be saved.
  405.  
  406.  
  407.  
  408.           Algorithm for Saving Undo Events
  409.           --------- ---    ------ ---- ------
  410.  
  411. I save undo events as they occur.  I leave it to the undo routine to
  412. figure out how to undo this type of event because its easy, undo has
  413. more time to do it and this routine should be as fast as possible
  414. because most undo events will never be used and you want the editor to
  415. keep up with you.
  416.  
  417.      save_for_undo(type,n)
  418.        int type;    /* event type:  BU_INSERT, etc */
  419.        int n;        /* number of characters involved (if any) */
  420.      {
  421.        Undo undo;
  422.        UnMark mark;
  423.  
  424.        if (!do_undo) return;    /* don't save undos for this buffer */
  425.  
  426.        switch (type)
  427.        {
  428.      case BU_INSERT:            /* Characters inserted */
  429.        set_unmark(&mark);
  430.        pack_sequential_insert_events();
  431.  
  432.        undo.n = n;
  433.        undo.mark = mark;
  434.  
  435.        break;
  436.      case BU_DELETE:            /* Characters deleted */
  437.      {
  438.        if (n == 0) return;            /* that was easy! */
  439.  
  440.        set_unmark(&mark);
  441.        undo.mark = mark;
  442.        open_bag(n);             /* make sure there is enough space */
  443.        undo.n = save_text(n);    /* returns number of characters saved */
  444.  
  445.        break;
  446.      }
  447.      case BU_SP:                /* Set sequence point */
  448.        if (last_event_was_a_sequence_point()) return;
  449.        break;
  450.      case BU_UNCHANGED:        /* Buffer has been marked safe */
  451.        if (last_event_was_a_save()) return;
  452.        header->there_is_a_valid_unchanged_event = TRUE;
  453.        break;
  454.        }
  455.  
  456.        undo.type = type;
  457.  
  458.        push_undo(&undo);
  459.      }
  460.  
  461.  
  462.  
  463.              Algorithm for Undoing Events
  464.              --------- --- ------- ------
  465.  
  466. This routine performs undo by reversing the effects of undo events from
  467. most recent until it finds a sequence point or runs out of events.
  468.  
  469. Note that undo is turned off so we don't try and re-save undo events as
  470. we march through the stack.
  471.  
  472. If the last event undid was a UNCHANGED, we need to add a new one to the
  473. undo list (to replace the one we popped).  If we don't, when we undo
  474. back to this point in the future, there won't be a UNCHANGED event to
  475. tell us the buffer is unchanged.  Ditto if we empty the undo stack.
  476.  
  477. UNCHANGED events are a no-op if the buffer is not modified.  This makes
  478. <save buffer><undo> work "nicer" and lets the above work (if it wasn't,
  479. undo would stop at the UNCHANGED event and you couldn't undo any more).
  480.  
  481.      undo()
  482.      {
  483.        int undo_flag, num_events, something_happened, push_an_unchanged;
  484.        Undo *ptr;
  485.  
  486.        if (no_undos()) return;
  487.  
  488.        undo_flag = do_undo; do_undo = FALSE;
  489.  
  490.        num_events = 0;
  491.        something_happened = FALSE;
  492.        push_an_unchanged = FALSE;
  493.  
  494.        while (ptr = pop_undo())
  495.        {
  496.      num_events++;
  497.      switch (ptr->type)
  498.      {
  499.        case BU_INSERT:    /* To undo: Delete inserted characters */
  500.          something_happened = TRUE;
  501.          goto_unmark(&ptr->mark);
  502.          delete_text(ptr->n);
  503.          break;
  504.        case BU_DELETE:    /* To undo: Insert deleted characters */
  505.          something_happened = TRUE;
  506.          goto_unmark(&ptr->mark);
  507.          insert_block(ptr->text, ptr->n);
  508.          break;
  509.        case BU_UNCHANGED:    /* At this point, buffer might be unchanged */
  510.          if (header->there_is_a_valid_unchanged_event &&
  511.          buffer_is_modified())
  512.          {
  513.         buffer_modified(FALSE);
  514.         something_happened = TRUE;
  515.         push_an_unchanged = TRUE;
  516.          }
  517.          header->there_is_a_valid_unchanged_event = FALSE;
  518.          /* fall through:  a BU_UNCHANGED acts like a sequence point */
  519.        case BU_SP:        /* Hit a sequence point, stop undoing */
  520.          if (something_happened) goto done;
  521.          break;
  522.      }
  523.        }
  524.  
  525.      done:
  526.  
  527.        gc_undos(num_events);    /* clean up the undo stack needed */
  528.  
  529.        do_undo = undo_flag;
  530.  
  531.        if (push_an_unchanged || (undo_stack_empty() && buffer_not_modified()))
  532.          save_for_undo(BU_UNCHANGED,0);
  533.      }
  534.  
  535.  
  536.  
  537.                Miscellaneous Algorithms
  538.                ------------- ----------
  539.  
  540. Here are some miscellaneous routines to flesh out undo.  Note that there
  541. are a lot missing, for example undo stack management and garbage
  542. collection.  The routines presented here aren't as "clean" as I'd like
  543. because they have to know how the undo stack is implemented.
  544.  
  545. Note:  When I say walk the stack, I mean move towards the older events.
  546. I do this because it is easy and in the case of undo() and thats what you
  547. want.
  548.  
  549.  
  550. The next routine is used to make space available to hold a copy of the
  551. text that will be deleted.  Basically, it figures out which (if any) of
  552. the older events need to be removed from the stack to make room in the
  553. bag.  It does this by looking at delete events (the only event that
  554. saves text) and finding an event such that by deleting that event and all
  555. older events, it will remove the minimum number of events necessary to
  556. free enough space so that the bag can hold space_needed more characters.
  557. The key here is that the number of characters in the bag is the sum of
  558. all delete events (the n in the Undo stucture).  Note it would be
  559. faster, in general, to walk the stack backwards (from oldest event to
  560. youngest) and find the first event that met the requirements but that is
  561. not possible the way I implemented the stacks.
  562.  
  563.  
  564.      /* Check to see if space_needed is available in the bag.  If not,
  565.       *   try and pack the bag and stack to make enough room.  If more
  566.       *   space is requested than we allow, clear the stack because if
  567.       *   we can't save this undo, every undo before this one is
  568.       *   invalid.
  569.       * Returns:
  570.       *   TRUE:  Bag (now) has enough room.
  571.       *   FALSE:  You want too much space and can't have it.  Undo stack
  572.       *     cleared.  Try again with a more reasonable request.
  573.       */
  574.      static int open_bag(space_needed) int space_needed;
  575.      {
  576.        int tot, da_total, total_so_far;
  577.        Undo *ptr, *da_winner;
  578.        UndoHeader *header;
  579.  
  580.        header = <the undo header for the current buffer>;
  581.  
  582.        total_so_far = bag_size(header->bag); /* number of characters in bag */
  583.        tot = space_needed -(max_undo_saved -total_so_far);
  584.  
  585.        if (tot <= 0) return TRUE;        /* Plenty of room! */
  586.  
  587.        if (space_needed > max_undo_saved)    /* You want too much! */
  588.        {
  589.      clear_undos();
  590.      return FALSE;
  591.        }
  592.  
  593.        da_winner = NULL;
  594.        for (ptr = <walk undo stack starting at the most recent event>)
  595.        {
  596.      if (ptr->type == BU_DELETE)
  597.      {
  598.        if (total_so_far >= tot)    /* found enough space here */
  599.        {
  600.          da_winner = ptr;
  601.          da_total = total_so_far;
  602.        }
  603.        else break;        /* the last one was the one we wanted */
  604.        total_so_far -= ptr->n;
  605.      }
  606.        }
  607.  
  608.        /* We KNOW (and can prove it) that da_winner != NULL because
  609.         *   bag_size >= tot > max - bag_size
  610.         *   (from
  611.         *   max_undo_saved >= space_needed > max_undo_saved -bag_size
  612.         *   among other things).  Since bag_size is the sum of all the
  613.         *   BU_DELETEs, there must be one or more events that are
  614.         *   winners.
  615.         */
  616.        for (ptr = <walk undo stack starting at da_winner>)
  617.        {
  618.      free_undo(ptr);
  619.        }
  620.        pack_bag(da_total);    /* remove text from bag, fix up pointers */
  621.  
  622.        return TRUE;
  623.      }
  624.  
  625.  
  626.      /* Go though the undo stack and adjust the text indices to reflect
  627.       * n characters being removed from the front of the bag.  Shift n
  628.       * characters off the front of the bag.
  629.       */
  630.      static void pack_bag(n) int n;
  631.      {
  632.        Undo *ptr;
  633.        UndoHeader *header;
  634.  
  635.        header = <the undo header for the current buffer>;
  636.  
  637.        for (ptr = <walk undo stack starting at the most recent event>)
  638.      if (ptr->type == BU_DELETE)
  639.      {
  640.        <adjust ptr->text back by n characters>
  641.      }
  642.  
  643.         /* remove n characters from front of bag */
  644.        slide_bag(header->bag,n);
  645.      }
  646.  
  647.  
  648. Here are a couple of routines that you will need if you have a LLE.
  649. This is how to calculate and use undo marks.
  650.  
  651.      static void goto_unmark(mark) UnMark *mark;
  652.      {
  653.        goto_line(mark->line);
  654.        next_character(mark->offset);
  655.      }
  656.  
  657.      static void set_unmark(mark) UnMark *mark;
  658.      {
  659.        extern Mark *the_dot;    /* the dot in the current buffer */
  660.  
  661.        register Line *lp, *dot_line;
  662.        register int line;
  663.  
  664.        dot_line = the_dot->line;
  665.        for (line = 1, lp = BUFFER_FIRST_LINE(current_buffer);
  666.         lp != dot_line; lp = lp->l_next)
  667.      line++;
  668.  
  669.        mark->line = line;
  670.        mark->offset = the_dot->offset;
  671.      }
  672.